import os

import pandas as pd
import openpyxl
import xlrd
import shutil
import Zip

def row2str(row_data):
    values = ""
    for i in range(len(row_data)):
        if i == len(row_data) - 1:
            values = values + str(row_data[i])
        else:
            values = values + str(row_data[i]) + ","
    return values

# 处理xlsx
def fun(filename, i):
    # 源文件
    src_file = Zip.src_dicname + i + '/' + filename
    # 目标文件
    target = Zip.target_dicname + i + '/' + filename.split('.')[0] + '.txt'
    # 错误文件
    wrong = Zip.wrong + i
    # 错误日志
    log = Zip.log + i + '/wrong.txt'

    try:
        wb = openpyxl.load_workbook(src_file)
        sheets = wb.sheetnames
        for sheet in sheets:
            # print(sheet)
            df = pd.read_excel(src_file, sheet_name=sheet, header=None)
            # print('开始写入txt文件...')
            # 保存txt文件
            df.to_csv(target, header=None, sep=',', index=False)
            # print('文件写入成功!')
    except BaseException as e:
        if not os.path.exists(Zip.wrong + i):
            os.makedirs(Zip.wrong + i)  # 创建路径
        shutil.move(src_file, wrong + "/")
        with open(log, "a") as file:  # "a"代表追加内容
            file.write(filename + " " + repr(e) + "\n")


# 处理xls格式的数据
def fun2(filename,i):
    # 源文件
    src_file = Zip.src_dicname + i + '/' + filename
    # 目标文件
    target = Zip.target_dicname + i + '/' + filename.split('.')[0] + '.txt'
    # 错误文件
    wrong = Zip.wrong + i
    # 错误日志
    log = Zip.log + i + '/wrong.txt'

    try:
        data = xlrd.open_workbook(src_file)
        file = open(target, "a")
        # 表头
        table = data.sheets()[0]
        # 行数
        row_cnt = table.nrows
        # 列数
        col_cnt = table.ncols
        title = table.row_values(0)

        for j in range(1, row_cnt):
            row = table.row_values(j)
            # 调用函数，将行数据拼接成字符串
            row_values = row2str(row)
            # 将字符串写入新文件
            file.writelines(row_values + "\r")
        # 关闭写入的文件
        file.close()
    except BaseException as e:
        if not os.path.exists(Zip.wrong + i):
            os.makedirs(Zip.wrong + i)  # 创建路径
        shutil.move(src_file, wrong + "/")
        with open(log, "a") as file:  # "a"代表追加内容
            file.write(filename + " " + repr(e) + "\n")


